<?php

class CustomersController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAr($custno)
    {


        $this->render('ar', array(
            'model' => $customer,
        ));
    }

    public function actionAjaxView($id)
    {

        $rs = $this->loadModel($id)->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Customers;
        $model->latecharge = 0.0;

        $model->discount = 0.0;
        $model->emailstatement = 1;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Customers']))
        {
            $model->attributes = $_POST['Customers'];
            if ($model->save())
            {

                $this->redirect(array('update', 'id' => $model->custno));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);


        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Customers']))
        {

            $model->attributes = $_POST['Customers'];
            $model->save();
        }
		 $globalContacts = Locationcontacts::model()->findAll("locno='00000' and custno='$model->custno'");
        foreach ($globalContacts as $contact)
        {
            $data[$contact->email] = 'G: '.$contact->contact . ' - ' . $contact->email . ' - ' . $contact->jobtitle;
        }
        $presidentContract = Employees::model()->findByPk('1109');
        if ($presidentContract != null)
        {
            $data[$presidentContract->workemail] = 'Greg Cahoe' . ' - ' . $presidentContract->workemail;
        }

        if (empty($data))
            $data = array('N/A', 'N/A');
        outputJsByList($data, 'contacts');
        
        //troy
        outputJsByList(Dispatchdetails::model()->getDepartmentList(), 'department');
        outputJsByList(Dispatchdetails::model()->getPriorityList(), 'priority');        
        //troy

        $arContent = $this->renderArTab($model);
        $this->render('update', array(
            'model' => $model,
            'arContent' => $arContent
        ));
    }

    public function renderArTab($model)
    {
        $openInvoice = $model->getOpenInvoiceAmount();
        $openInvoiceList = $model->getOpenInvoiceList();
        $credit = $model->getTotalCredit();
        $creditInvoiceList = $model->getInvoiceCreditList();

        $pp = $model->getTotalDeposit();
        $depositInvoiceList = $model->getInvoiceDepositList();

        $creditMemoAmount = $model->getCreditMemoAmount();
        $creditMemoList = $model->getCreditMemoList();
        return $this->renderPartial('ar', array(
                    'openInvoice' => $openInvoice,
                    'credit' => $credit,
                    'creditInvoiceList' => $creditInvoiceList,
                    'pp' => $pp,
                    'depositInvoiceList' => $depositInvoiceList,
                    'subTotal' => $openInvoice - $credit,
                    'total' => $openInvoice - $credit - $pp,
                    'openInvoiceList' => $openInvoiceList,
                    'creditMemoAmount' => $creditMemoAmount,
                    'creditMemoList' => $creditMemoList
                        ), true);
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Customers');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Customers::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'customers-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /*
     * Param: query, page, sort, dir
     * Get customer list
     * return json array totalCount and array of customer
     */

    public function actionGetCustomerList($query=NULL, $page=1, $sort=NULL, $dir=NULL, $status=0)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $crit = new CDbCriteria();
        $order = CJSON::decode($sort);
        if ($order != NULL)
        {
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }
        else
        {
            $crit->order = 'custno';
        }
        if ($query != NULL)
        {
            $crit->compare('custno', $query, true);
            $crit->compare('lastname', $query, true, 'or');
            $crit->compare('add1', $query, true, 'or');
            $crit->compare('city', $query, false, 'or');
        }
		
		if ($status != NULL)
		{
		    $crit->compare('customerinactive', $status, false, 'and');   
		}
		
        $customers = new CActiveDataProvider('Customers', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $rs = array();
        if ($customers->getTotalItemCount() > 0)
        {
            $rs['totalCount'] = $customers->getTotalItemCount();
            $rs['type'] = 'Customers';
            foreach ($customers->getData() as $item)
            {
                $rs['data'][] = $item->getAttributes();
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

    public function actionGetCustomer($query)
    {
        $customer = Customers::model()->find('id=:id', array('id' => $query));
        $rs = $customer->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
    }

    public function actionPopupCreateCustomer()
    {
        $this->layout = 'popup';
        $model = new Customers;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Customers']))
        {
            $model->attributes = $_POST['Customers'];
            if ($model->save())
            {

                $this->redirect(array('view', 'id' => $model->custno));
            }
        }
        $this->render('popupCreateCustomer', array(
            'model' => $model,
        ));
    }

    public function actionServiceContractReport($custno)
    {
        $customerModel = $this->loadModel($custno);

        if ($customerModel != null)
        {
            $schedulePaymentList = array();
            $totalAmount = 0;
            $billType = null;
            $totalCount = 0;
            foreach ($customerModel->serviceContractModelList as $contract)
            {
                if ($billType == null)
                {
                    $billType = $contract->billtype;
                }
                else if ($billType != $contract->billtype)
                {
                    throw new CHttpException('Contract type conficts other at contract number:' . $contract->contractid);
                }

                $totalAmount+=$contract->contractamount;

                //$totalSchedulePaymentList=array_merge($totalSchedulePaymentList, $contract->schedulePaymentModelList);
                foreach ($contract->schedulePaymentModelList as $schedulePayment)
                {
                    $schedulePaymentList[$schedulePayment->number][] = $schedulePayment->amount;

                    $totalCount++;
                }
            }
            $this->render('serviceContractReport', array(
                'billtype' => $billType,
                'customerModel' => $customerModel,
                'contractModelList' => $customerModel->serviceContractModelList,
                'totalAmount' => $totalAmount,
                'schedulePaymentList' => $schedulePaymentList,
                'totalCount' => $totalCount
            ));
        }
    }

    public function actionDetails($custno)
    {
        $model = Customers::model()->find('custno=:custno', array(
            'custno' => $custno
                ));
        if ($model != null)
        {
            $this->showAjaxMessage(json_encode($model->attributes), true);
        }
        else
        {
            $this->showAjaxMessage('Customer can not be found');
        }
    }

    public function actionInvoiceReport($custno=null, $pdf=0, $ajax=0)
    {
        assert('is_numeric($pdf)');
        assert('is_numeric($ajax)');
        assert('is_string($custno)');

        if ($pdf)
        {
            Yii::import('application.extensions.MPDF53.*');
            require_once('mpdf.php');
            $mpdf = new mPDF();
            $stylesheet = file_get_contents('css/InvoiceReport.css');
            $mpdf->SetDisplayMode('fullpage');
            $mpdf->WriteHTML($stylesheet, 1);
            $mpdf->SetFooter('{PAGENO}');
        }

        if ($custno != null)
        {
            $customerModel = $this->loadModel($custno);
            $html = $this->generateInvoiceReportFromInvoiceAndSalesOrderList(
                    $customerModel->invoiceModelList, $this->getNotFullyInvoicedAndNoDepositSalesOrderList($customerModel), $customerModel, false
            );
            if ($pdf)
            {
                $mpdf->WriteHTML($html);
            }
        }
        else
        {
            $customerModelList = Customers::model()->findAll();
            $i = 0;
            $html = '';
            foreach ($customerModelList as $customer)
            {
                $noHeader = $i == 0 ? false : true;
                $html = $this->generateInvoiceReportFromInvoiceAndSalesOrderList(
                        $customer->invoiceModelList, $this->getNotFullyInvoicedAndNoDepositSalesOrderList($customer), $customer, $noHeader);
                if ($pdf)
                {
                    $mpdf->WriteHTML($html);
                    $html = '';
                    if ($i < count($customerModelList) - 1)
                    {
                        $mpdf->AddPage();
                    }
                }
                $i++;
            }
            //echo $html;
        }
        if ($pdf)
        {
            $name = 'pdf/AccountStatement_' . date('m-d-Y H_i_s') . '.pdf';
            $mpdf->Output($name);

            if ($ajax)
            {
                if (is_file($name) && file_exists($name))
                {
                    $this->showAjaxMessage(array(
                        'filename' => $name,
                            ), true);
                }
            }
        }
        else
        {
            if ($ajax)
            {
                $this->showAjaxMessage(array(
                    'html' => $html,
                        ), true);
            }
            else
            {
                echo $html;
            }
        }
    }

    protected function getNotFullyInvoicedAndNoDepositSalesOrderList($customer)
    {
        $list = Invoice::model()->findAll(array(
            'alias' => 'i1',
            'condition' => "((select sum(i2.amountcharge) from tbl_invoice i2 where i2.salesordersorg = i1.invoice) < i1.amountcharge 
                                or not exists(select i3.* from tbl_invoice i3 where i3.salesordersorg = i1.invoice and i3.invoicetype=:invoicetype))
                            and custno=:custno and invoicetype=:type and not exists(select r.* from tbl_rec_led_apply r where r.type=:appliedtype and r.number= i1.invoice)
                ",
            'params' => array(
                'custno' => $customer->custno,
                'type' => Invoice::TYPE_SALES_ORDERS,
                'invoicetype' => Invoice::TYPE_INVOICE,
                'appliedtype' => RecLed::TYPE_APPLIED
            )
                ));
        return $list;
    }

    protected function generateInvoiceReportFromInvoiceAndSalesOrderList(
    $invoiceModelList, $salesOrderModelList, $customerModel, $noHeader=true)
    {

        $companyName = null;
        if ($customerModel != null)
        {
            $companyName = $customerModel->firstname . ' ' . $customerModel->lastname;
        }
        //process invoice
        $invoiceData = array();
        $totalDueOfInvoice = 0;
        $invoiceTotal = 0;
        foreach ($invoiceModelList as $invoice)
        {
            /* @var $invoice Invoice */
            $invoiceData[$invoice->invoice] = $invoice->attributes;
            $invoiceData[$invoice->invoice]['department']=SalesDepartments::getText($invoice->department);
            $invoiceData[$invoice->invoice]['date']=convertDate('m-d-Y',$invoice->invoicedate);
            $balance = $invoice->amountcharge;
            $invoiceData[$invoice->invoice]['payments']=array();
            foreach ($invoice->invoicePaymentList as $payment)
            {
                $invoiceData[$invoice->invoice]['payments'][$payment->id] = $payment->attributes;
                $invoiceData[$invoice->invoice]['payments'][$payment->id]['date']=convertDate('m-d-Y',$payment->applieddate);
                $balance-= $payment->paid;
            }
            $invoiceData[$invoice->invoice]['balance'] = $balance;
            $totalDueOfInvoice+=$balance;
            $invoiceTotal+=$invoice->amountcharge;
        }
        
        $salesOrderData= array();        
        $totalSalesOrder=0;
        $totalDeposit =0;
        $totalUnInvoiced = 0;
        foreach($salesOrderModelList as $salesOrder){
            /* @var $salesOrder Invoice */
            $totalUnInvoiced +=$salesOrder->amountcharge;
            $totalSalesOrder+=$salesOrder->amountcharge;
            $salesOrderData[$salesOrder->invoice] = $salesOrder->attributes;
            $salesOrderData[$salesOrder->invoice]['department']=SalesDepartments::getText($salesOrder->department);
            $salesOrderData[$salesOrder->invoice]['date']=convertDate('m-d-Y',$salesOrder->invoicedate);            
            $invoiceList = $salesOrder->findInvoiceModelListFromSalesOrder();
            $saInvoiceData= array();
            foreach($invoiceList as $invoice){
                $totalUnInvoiced -=$invoice->amountcharge;
                $saInvoiceData[]=array(
                    'invoice'=>$invoice->invoice,
                    'amountcharge'=>$invoice->amountcharge
                );
            }
            $salesOrderData[$salesOrder->invoice]['invoices']=$saInvoiceData;
            $salesOrderData[$salesOrder->invoice]['payments']=array();
            $paymentTotal=0;
            $balance =$salesOrder->amountcharge;
            foreach($salesOrder->salesOrderPaymentList as $payment){
                if($payment->type == RecLed::TYPE_DP){
                    $salesOrderData[$salesOrder->invoice]['payments'][$payment->id] = $payment->attributes;
                    $salesOrderData[$salesOrder->invoice]['payments'][$payment->id]['date'] =convertDate('m-d-Y', $payment->applieddate);
                    $balance -= $payment->paid;
                    $totalDeposit +=$payment->paid;
                    $paymentTotal+=$payment->paid;
                }                
            }
            $salesOrderData[$salesOrder->invoice]['paymentTotal'] = $paymentTotal;
            $salesOrderData[$salesOrder->invoice]['balance'] = $balance;
        }
        
        return $this->render('invoiceReport', array(
                    'noHeader' => $noHeader,
                    'companyName' => $companyName,
                    'customerModel'=>$customerModel,
                    'totalDueOfInvoice' => $totalDueOfInvoice,
                    'totalInvoice'=>$invoiceTotal,
                    'totalSalesOrder' => $totalSalesOrder,
                    'customerSalesOrderTotal'=>$customerModel->getTotalSalesOrderAmount(),
                    'totalUnInvoiced' => $totalUnInvoiced,
                    'totalDeposit' => $totalDeposit,
                    'invoiceData'=>$invoiceData,
                    'salesOrderData'=>$salesOrderData
                        ), true);
    }

}
